import React, { Component } from 'react'
import store from '../../redux/store'
import {
  createIncrementAction,
  createDecrementAction
} from '../../redux/count_action'

export default class Count extends Component {
  state = {
    carName: '奔驰'
  }

  componentDidMount() {
    // 检测 redux 中的状态发生变化，只要变化，就调用 render，
    // 通过 store.subscribe(() => {}) 订阅方法实现
    store.subscribe(() => {
      this.setState({})
    })
  }

  // 相加
  increment = () => {
    const { value } = this.selectNum
    store.dispatch(createIncrementAction(+value))
  }

  // 相减
  decrement = () => {
    const { value } = this.selectNum
    store.dispatch(createDecrementAction(+value))
  }

  // 和是奇数再加
  incrementIfodd = () => {
    if (store.getState() % 2) {
      const { value } = this.selectNum
      store.dispatch(createIncrementAction(+value))
    }
  }

  // 异步加
  incrementAsyc = () => {
    setTimeout(() => {
      const { value } = this.selectNum
      store.dispatch(createIncrementAction(+value))
    }, 500)
  }

  render() {
    // const { count } = this.state
    return (
      <div>
        当前 count 值为 {store.getState()}
        <div>
          <select ref={(c) => (this.selectNum = c)}>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
          </select>
          <button onClick={this.increment}>increment</button>
          <button onClick={this.decrement}>decrement</button>
          <button onClick={this.incrementIfodd}>incrementIfodd</button>
          <button onClick={this.incrementAsyc}>incrementAsyc</button>
        </div>
      </div>
    )
  }
}
